﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Web.Mvc;
using Test.Common;
using Test.Utility.Extensions;

namespace Test.Site.Data.Helper
{
    public static class SelectListItemsHelper
    {

        public static IList<SelectListItem> FromEnum<TEnum>()
        {
            Type enumType = typeof(TEnum);
            return FromEnum(enumType);
        }
        
        public static IList<SelectListItem> FromEnum(Type enumType, string extraFirstItem = null, object selectedValue = null, params string[] includeItems)
        {
            string cacheName = string.Format("{0}_{1}_{2}", enumType.ToString(), extraFirstItem??"", includeItems.JoinToString());

            //var cacheSelectItems = SiteCache.Get(cacheName, () =>
            //{
                IList<SelectListItem> list = new List<SelectListItem>();

                if (extraFirstItem.IsNotNullAndNotWhiteSpace())
                {
                    var selected = selectedValue.AsString().IsNullOrWhiteSpace();
                    list.Add(new SelectListItem { Text = extraFirstItem, Value = ""});
                }

                foreach (var field in enumType.GetFields(BindingFlags.Static | BindingFlags.Public))
                {
                    var notSupported = field.GetCustomAttributes(typeof(NotSupported)).Any();

                    if (notSupported ||
                        (includeItems.IsNotEmpty() && !includeItems.Contains(field.Name)))
                    {
                        continue;
                    }

                    var descAttr = field.GetCustomAttributes(typeof(DescriptionAttribute), false)
                                        .OfType<DescriptionAttribute>()
                                        .FirstOrDefault();

                    var text = descAttr == null ? field.Name : descAttr.Description;
                    var value = field.Name;

                    list.Add(new SelectListItem { Text = text, Value = value});
                }

                //return list;
            //});

            var result = list.ToList();

            result.ForEach(item =>
            {
                item.Selected = selectedValue != null && item.Value == selectedValue.ToString();
            });

            return result;
        }
    }
}
